﻿using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using XYS.Service.Core.Models;

namespace XYS.Core.Util.Helper
{
    /// <summary>
    /// 枚举 帮助类
    /// </summary>
    public partial class EnumHelper
    {
        /// <summary>
        /// 获取枚举 描述
        /// TODO :由于反射消耗较大性能。所以需要考虑增加缓存
        /// </summary>
        /// <param name="value">枚举</param>
        /// <returns></returns>
        public static string GetDescription(object value)
        {
            if (value == null) { return null; }

            System.Reflection.MemberInfo member = value.GetType().GetMembers().FirstOrDefault(e => e.Name.ToUpper() == value.ToString().ToUpper());
            if (member == null) return nameof(value);

            DescriptionAttribute descriptionAttribute = member.GetCustomAttributes(typeof(DescriptionAttribute), true).Select(a => a as DescriptionAttribute).FirstOrDefault();
            string description = descriptionAttribute?.Description;

            if (string.IsNullOrEmpty(description))
            {
                DisplayAttribute displayAttribute = member.GetCustomAttributes(typeof(DisplayAttribute), true).Select(a => a as DisplayAttribute).FirstOrDefault();
                return displayAttribute?.GetName() ?? value.ToString();
            }
            return description;
        }


        /// <summary>
        /// 计算一个枚举类型中所有枚举项 按位或运算结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T EnumBitwiseOrResults<T>()
            where T : Enum
        {
            var enumValues = Enum.GetValues(typeof(T));
            int result = 0;
            foreach (T value in enumValues)
            {
                result |= Convert.ToInt32(value);
            }
            return (T)Enum.ToObject(typeof(T), result);
        }

        /// <summary>
        /// 枚举值转List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<T> ToList<T>() where T : Enum
        {
            return GetValues<T>().ToList();
        }

        /// <summary>
        /// 遍历枚举值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IEnumerable<T> GetValues<T>() where T : Enum
        {
            return Enum.GetValues(typeof(T)).Cast<T>();
        }



    }
}
